package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class PurchaseItemServlet
 */
@WebServlet(urlPatterns = { "/PurchaseItem", "/purchaseItem", "/PurchaseItemServlet", "/purchaseItemServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class PurchaseItemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public PurchaseItemServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<PurchaseItemModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				response.sendRedirect("purchaseItemNew.jsp");
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			PurchaseItemModel query = new PurchaseItemModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PurchaseItemModel, PurchaseItemModelExt> dal = new GenericDal<PurchaseItemModel, PurchaseItemModelExt>(new PurchaseItemModel());

			PurchaseItemModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("purchaseItem", obj);
				getServletContext().getRequestDispatcher("/purchaseItemEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			PurchaseItemModel query = new PurchaseItemModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PurchaseItemModel, PurchaseItemModelExt> dal = new GenericDal<PurchaseItemModel, PurchaseItemModelExt>(new PurchaseItemModel());

			PurchaseItemModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("purchaseItem", obj);
				getServletContext().getRequestDispatcher("/purchaseItemView.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("delete")) {

			PurchaseItemModel query = new PurchaseItemModel();
			String strId = request.getParameter("id");
			int idPurchase = 0;
			idPurchase = Integer.parseInt(request.getParameter("idPurchase"));
			String purchaseUrl = "purchaseItemList.jsp?idPurchase=" + idPurchase;

			int id = Integer.parseInt(strId);
			query.setId(id);

			GenericDal<PurchaseItemModel, PurchaseItemModelExt> dal = new GenericDal<PurchaseItemModel, PurchaseItemModelExt>(new PurchaseItemModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect(purchaseUrl);
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		} 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			PurchaseItemModel obj = new PurchaseItemModel();
			String id_purchase = request.getParameter("id_purchase");
                if (id_purchase != null && !id_purchase.isEmpty()) {
				    obj.setIdPurchase(Integer.parseInt(id_purchase));
                }

String id_product = request.getParameter("id_product");
                if (id_product != null && !id_product.isEmpty()) {
				    obj.setIdProduct(Integer.parseInt(id_product));
                }


//String from_date_date = request.getParameter("from_date_date");
//String from_date_time = request.getParameter("from_date_time");
//if (from_date_date != null && !from_date_date.isEmpty() && from_date_time != null && !from_date_time.isEmpty()) {
//        obj.setFromDate(DateTimeUtil.parseDateTime(from_date_date, from_date_time));
//} else {
//obj.setFromDate(DateTimeUtil.parseDate(from_date_date));
//}
//
//
//String to_date_date = request.getParameter("to_date_date");
//String to_date_time = request.getParameter("to_date_time");
//if (to_date_date != null && !to_date_date.isEmpty() && to_date_time != null && !to_date_time.isEmpty()) {
//        obj.setToDate(DateTimeUtil.parseDateTime(to_date_date, to_date_time));
//} else {
//obj.setToDate(DateTimeUtil.parseDate(to_date_date));
//}

String quantity = request.getParameter("quantity");
                if (quantity != null && !quantity.isEmpty()) {
				    obj.setQuantity(Double.parseDouble(quantity));
                }

String id_unit = request.getParameter("id_unit");
                if (id_unit != null && !id_unit.isEmpty()) {
				    obj.setIdUnit(Integer.parseInt(id_unit));
                }

//String unit_price = request.getParameter("unit_price");
//                if (unit_price != null && !unit_price.isEmpty()) {
//				    obj.setUnitPrice(Integer.parseInt(unit_price));
//                }
//
//String total_price = request.getParameter("total_price");
//                if (total_price != null && !total_price.isEmpty()) {
//				    obj.setTotalPrice(Double.parseDouble(total_price));
//                }
//
//String note = request.getParameter("note");
//				obj.setNote(note);

String status = request.getParameter("status");
                if (status != null && !status.isEmpty()) {
				    obj.setStatus(Integer.parseInt(status));
                }

//String is_draft = request.getParameter("is_draft");
//				obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//						|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//                if (notification != null && !notification.isEmpty()) {
//				    obj.setNotification(Integer.parseInt(notification));
//                }



String id_service = request.getParameter("id_service");
                if (id_service != null && !id_service.isEmpty()) {
				    obj.setIdService(Integer.parseInt(id_service));
                }

//String name = request.getParameter("name");
//				obj.setName(name);

//String code = request.getParameter("code");
//				obj.setCode(code);

String item_price = request.getParameter("item_price");
                if (item_price != null && !item_price.isEmpty()) {
				    obj.setItemPrice(Double.parseDouble(item_price));
                }

String discount = request.getParameter("discount");
                if (discount != null && !discount.isEmpty()) {
				    obj.setDiscount(Double.parseDouble(discount));
                }


                String plan_delivery_time_date = request.getParameter("plan_delivery_time_date");
                String plan_delivery_time_time = request.getParameter("plan_delivery_time_time");
                if (plan_delivery_time_date != null && !plan_delivery_time_date.isEmpty() && plan_delivery_time_time != null && !plan_delivery_time_time.isEmpty()) {
                        obj.setPlanDeliveryTime(DateTimeUtil.parseDateTime(plan_delivery_time_date, plan_delivery_time_time));
            } else {
                obj.setPlanDeliveryTime(DateTimeUtil.parseDate(plan_delivery_time_date));
            }


                String real_delivery_time_date = request.getParameter("real_delivery_time_date");
                String real_delivery_time_time = request.getParameter("real_delivery_time_time");
                if (real_delivery_time_date != null && !real_delivery_time_date.isEmpty() && real_delivery_time_time != null && !real_delivery_time_time.isEmpty()) {
                        obj.setRealDeliveryTime(DateTimeUtil.parseDateTime(real_delivery_time_date, real_delivery_time_time));
            } else {
                obj.setRealDeliveryTime(DateTimeUtil.parseDate(real_delivery_time_date));
            }

String requester = request.getParameter("requester");
                if (requester != null && !requester.isEmpty()) {
				    obj.setRequester(Integer.parseInt(requester));
                }

String description = request.getParameter("description");
				obj.setDescription(description);

String remark = request.getParameter("remark");
				obj.setRemark(remark);

String id_project = request.getParameter("id_project");
                if (id_project != null && !id_project.isEmpty()) {
				    obj.setIdProject(Integer.parseInt(id_project));
                }

String id_task = request.getParameter("id_task");
                if (id_task != null && !id_task.isEmpty()) {
				    obj.setIdTask(Integer.parseInt(id_task));
                }

String id_quotation = request.getParameter("id_quotation");
                if (id_quotation != null && !id_quotation.isEmpty()) {
				    obj.setIdQuotation(Integer.parseInt(id_quotation));
                }

String id_quotation_item = request.getParameter("id_quotation_item");
                if (id_quotation_item != null && !id_quotation_item.isEmpty()) {
				    obj.setIdQuotationItem(Integer.parseInt(id_quotation_item));
                }

String additional_cost = request.getParameter("additional_cost");
                if (additional_cost != null && !additional_cost.isEmpty()) {
				    obj.setAdditionalCost(Double.parseDouble(additional_cost));
                }
           
                String id_checklist = request.getParameter("id_checklist");
                if (id_checklist != null && !id_checklist.isEmpty()) {
				    obj.setIdChecklist(Integer.parseInt(id_checklist));
                }
                                
                String id_event = request.getParameter("id_event");
                if (id_event != null && !id_event.isEmpty()) {
				    obj.setIdEvent(Integer.parseInt(id_event));
                }


			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<PurchaseItemModel, PurchaseItemModelExt> dal = new GenericDal<PurchaseItemModel, PurchaseItemModelExt>(new PurchaseItemModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, refresh cache and redirect to somewhere
					String url = "purchaseItemList.jsp?idPurchase=" + obj.getIdPurchase();
					response.sendRedirect(url);
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("purchaseItem", obj);
				getServletContext().getRequestDispatcher("/purchaseItemInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			PurchaseItemModel query = new PurchaseItemModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PurchaseItemModel, PurchaseItemModelExt> dal = new GenericDal<PurchaseItemModel, PurchaseItemModelExt>(new PurchaseItemModel());

			PurchaseItemModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				
				String id_purchase = request.getParameter("id_purchase");
                if (id_purchase != null && !id_purchase.isEmpty()) {
				    obj.setIdPurchase(Integer.parseInt(id_purchase));
                }

String id_product = request.getParameter("id_product");
                if (id_product != null && !id_product.isEmpty()) {
				    obj.setIdProduct(Integer.parseInt(id_product));
                }


//String from_date_date = request.getParameter("from_date_date");
//String from_date_time = request.getParameter("from_date_time");
//if (from_date_date != null && !from_date_date.isEmpty() && from_date_time != null && !from_date_time.isEmpty()) {
//        obj.setFromDate(DateTimeUtil.parseDateTime(from_date_date, from_date_time));
//} else {
//obj.setFromDate(DateTimeUtil.parseDate(from_date_date));
//}
//
//
//String to_date_date = request.getParameter("to_date_date");
//String to_date_time = request.getParameter("to_date_time");
//if (to_date_date != null && !to_date_date.isEmpty() && to_date_time != null && !to_date_time.isEmpty()) {
//        obj.setToDate(DateTimeUtil.parseDateTime(to_date_date, to_date_time));
//} else {
//obj.setToDate(DateTimeUtil.parseDate(to_date_date));
//}

String quantity = request.getParameter("quantity");
                if (quantity != null && !quantity.isEmpty()) {
				    obj.setQuantity(Double.parseDouble(quantity));
                }

String id_unit = request.getParameter("id_unit");
                if (id_unit != null && !id_unit.isEmpty()) {
				    obj.setIdUnit(Integer.parseInt(id_unit));
                }

//String unit_price = request.getParameter("unit_price");
//                if (unit_price != null && !unit_price.isEmpty()) {
//				    obj.setUnitPrice(Integer.parseInt(unit_price));
//                }
//
//String total_price = request.getParameter("total_price");
//                if (total_price != null && !total_price.isEmpty()) {
//				    obj.setTotalPrice(Double.parseDouble(total_price));
//                }
//
//String note = request.getParameter("note");
//				obj.setNote(note);

String status = request.getParameter("status");
                if (status != null && !status.isEmpty()) {
				    obj.setStatus(Integer.parseInt(status));
                }

//String is_draft = request.getParameter("is_draft");
//				obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//						|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//                if (notification != null && !notification.isEmpty()) {
//				    obj.setNotification(Integer.parseInt(notification));
//                }



String id_service = request.getParameter("id_service");
                if (id_service != null && !id_service.isEmpty()) {
				    obj.setIdService(Integer.parseInt(id_service));
                }

//String name = request.getParameter("name");
//				obj.setName(name);

//String code = request.getParameter("code");
//				obj.setCode(code);

String item_price = request.getParameter("item_price");
                if (item_price != null && !item_price.isEmpty()) {
				    obj.setItemPrice(Double.parseDouble(item_price));
                }

String discount = request.getParameter("discount");
                if (discount != null && !discount.isEmpty()) {
				    obj.setDiscount(Double.parseDouble(discount));
                }


String plan_delivery_time_date = request.getParameter("plan_delivery_time_date");
String plan_delivery_time_time = request.getParameter("plan_delivery_time_time");
if (plan_delivery_time_date != null && !plan_delivery_time_date.isEmpty() && plan_delivery_time_time != null && !plan_delivery_time_time.isEmpty()) {
        obj.setPlanDeliveryTime(DateTimeUtil.parseDateTime(plan_delivery_time_date, plan_delivery_time_time));
} else {
obj.setPlanDeliveryTime(DateTimeUtil.parseDate(plan_delivery_time_date));
}


String real_delivery_time_date = request.getParameter("real_delivery_time_date");
String real_delivery_time_time = request.getParameter("real_delivery_time_time");
if (real_delivery_time_date != null && !real_delivery_time_date.isEmpty() && real_delivery_time_time != null && !real_delivery_time_time.isEmpty()) {
        obj.setRealDeliveryTime(DateTimeUtil.parseDateTime(real_delivery_time_date, real_delivery_time_time));
} else {
obj.setRealDeliveryTime(DateTimeUtil.parseDate(real_delivery_time_date));
}

String requester = request.getParameter("requester");
                if (requester != null && !requester.isEmpty()) {
				    obj.setRequester(Integer.parseInt(requester));
                }

String description = request.getParameter("description");
				obj.setDescription(description);

String remark = request.getParameter("remark");
				obj.setRemark(remark);

String id_project = request.getParameter("id_project");
                if (id_project != null && !id_project.isEmpty()) {
				    obj.setIdProject(Integer.parseInt(id_project));
                }

String id_task = request.getParameter("id_task");
                if (id_task != null && !id_task.isEmpty()) {
				    obj.setIdTask(Integer.parseInt(id_task));
                }

String id_quotation = request.getParameter("id_quotation");
                if (id_quotation != null && !id_quotation.isEmpty()) {
				    obj.setIdQuotation(Integer.parseInt(id_quotation));
                }

String id_quotation_item = request.getParameter("id_quotation_item");
                if (id_quotation_item != null && !id_quotation_item.isEmpty()) {
				    obj.setIdQuotationItem(Integer.parseInt(id_quotation_item));
                }

String additional_cost = request.getParameter("additional_cost");
                if (additional_cost != null && !additional_cost.isEmpty()) {
				    obj.setAdditionalCost(Double.parseDouble(additional_cost));
                }
                
                String id_checklist = request.getParameter("id_checklist");
                if (id_checklist != null && !id_checklist.isEmpty()) {
				    obj.setIdChecklist(Integer.parseInt(id_checklist));
                }
                else
                {
                	obj.setIdChecklist(Integer.MIN_VALUE);
                }
                                
                String id_event = request.getParameter("id_event");
                if (id_event != null && !id_event.isEmpty()) {
				    obj.setIdEvent(Integer.parseInt(id_event));
                }
                else
                {
                	obj.setIdEvent(Integer.MIN_VALUE);
                }


				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						String url = "purchaseItemList.jsp?idPurchase=" + obj.getIdPurchase();
						response.sendRedirect(url);
						
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("purchaseItem", obj);
					getServletContext().getRequestDispatcher("/purchaseItemList.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		}
	}

}